package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/admin/common/upload")
@Slf4j
@Api("文件上传")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping
    public Result upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extent = originalFilename.substring(originalFilename.lastIndexOf("."));
            UUID uuid = UUID.randomUUID();
            String newFileName = uuid + extent;

            String url = aliOssUtil.upload(file.getBytes(), newFileName);

            return Result.success(url);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

}
